package com.brainhealth.common.utils;

import java.util.ArrayList;
import java.util.List;

public final class ListUtil {

    public static <T> List<List<T>> averageAssign(List<T> source, int n)
    //注意传入的对象数值变动（切割的对象引用还是一个--导致多线程共用一个对象--出现线程安全问题）
    {
        List<List<T>> result = new ArrayList<>();
        if(source.size()<=n){
            result.add(source);
            return result;
        }
        int remainder = source.size() % n;
        int number = source.size() / n;
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value = new ArrayList<T>();
            if (remainder > 0) {
                List<T> flList = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                for (T t : flList) {
                    value.add(t);
                }
                remainder--;
                offset++;
            } else {
                List<T> flList = source.subList(i * number + offset, (i + 1) * number + offset);
                for (T t : flList) {
                    value.add(t);
                }
            }
            result.add(value);
        }
        return result;
    }

    public static <T> List<List<T>> partition(final List<T> list, final int groupSize) {
        if (list == null || list.isEmpty() || groupSize < 1) {
            return null;
        }

        int listSize = list.size();
        List<List<T>> result = new ArrayList<List<T>>();
        if(list.size()<=groupSize){
            result.add(list);
            return result;
        }
        int start = 0;
        int end = 0;
        while (start < listSize) {
            end = start + groupSize;
            if (end > listSize) {
                end = listSize;
            }
            List<T> subList = list.subList(start, end);
            result.add(subList);
            start = start + groupSize;
        }
        return result;
    }

}